import graphene
from flask import Flask
from flask_graphql import GraphQLView

from sqlalchemy import create_engine,Column,String
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm.session import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from uuid import uuid4
from graphene_sqlalchemy import SQLAlchemyObjectType

db = create_engine('mysql+pymysql://root:123@localhost:3306/graphql')
db_session = scoped_session(sessionmaker(bind=db))
Base = declarative_base()
Base.query = db_session.query_property()  # 获取查询对象

class EmployeeModel(Base):
    __tablename__ = 't_employee'
    id = Column(String(128),primary_key= True)
    name = Column(String(64))

class Employee(SQLAlchemyObjectType):
    class Meta:
        model = EmployeeModel
class CreateEmp(graphene.Mutation):
    emp = graphene.Field(Employee)
    flag = graphene.Boolean()
    class Arguments:
        id = graphene.String()
        name = graphene.String()
    def mutate(self,info,id, name):
        tmp_emp = EmployeeModel(id =id ,name =name)
        db_session.add(tmp_emp)
        db_session.commit()
        return CreateEmp(emp = tmp_emp, flag = True)

class Query(graphene.ObjectType):
    emps = graphene.List(Employee)
    emp = graphene.Field(Employee,id = graphene.String())

    def resolve_emps(self,info):
        query = Employee.get_query(info)
        return query.all()
    def resolve_emp(self,info,id):
        e1 = Employee.get_node(info,id)
        return e1
class Mutation(graphene.ObjectType):
    create_emp = CreateEmp.Field()

if __name__ =='__main__':
    schema = graphene.Schema(query=Query,mutation=Mutation)
    app = Flask(__name__)
    app.add_url_rule('/graphql',view_func=GraphQLView.as_view('grapql',schema=schema, graphiql=True))
    app.run(debug=True)